package com.openyelp.webstore.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.openyelp.webstore.utils.FileBackup;

@Component
public class UpImageWork2 {

	protected Upitem upfile(MultipartFile file, HttpServletRequest request,
			ModelMap model, String saveurls) {

		// 文件保存目录路径
		String savePath = request.getServletContext().getRealPath("/")
				+ "/attached/";

		// 文件保存目录URL
		// String saveUrl = request.getContextPath() + "/attached/";
		// 文件保存目录URL
		String saveUrl = saveurls;
		// 定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

		// 最大文件大小
		long maxSize = 1000000000;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return getErrorString("请选择文件。", model);
		}
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		if (!uploadDir.isDirectory()) {
			return getErrorString("上传目录不存在。", model);
		}
		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			return getErrorString("上传目录没有写权限。", model);
		}

		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if (!extMap.containsKey(dirName)) {
			return (getErrorString("目录名不正确。", model));
		}
		String app = request.getParameter("app");
		if (app == null) {
			app = "app";
		}
		UpConfig config=new UpConfig();
		config.setApp(app);
		// 创建文件夹
		savePath += app + "/";
		saveUrl += app + "/";
		File appDirFile = new File(savePath);
		if (!appDirFile.exists()) {
			appDirFile.mkdirs();
		}
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		Upitem itemss = new Upitem();

		if (file != null) {
			String fileName = file.getOriginalFilename();
			// 检查文件大小
			if (file.getSize() > maxSize) {
				return getErrorString("上传文件大小超过限制。", model);
			}
			// 检查扩展名
			String fileExt = FilenameUtils.getExtension(fileName).toLowerCase(
					Locale.ENGLISH);
			if (!Arrays.<String> asList(extMap.get(dirName).split(","))
					.contains(fileExt)) {
				return getErrorString(
						"上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。",
						model);
			}

			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + "." + fileExt;
			try {
				File uploadedFile = new File(savePath, newFileName);
				;
				// file.g
				FileUtils.writeByteArrayToFile(uploadedFile, file.getBytes());
				FileBackup.BackupFile(uploadedFile,config);
				// item.write(uploadedFile);
			} catch (Exception e) {
				return getErrorString("上传文件失败。", model);
			}
			itemss.setError(0);
			itemss.setUrl(saveUrl + newFileName);
			return itemss;
		}else{
			itemss.setError(-1);
		}
		return itemss;
	}


	private Upitem getErrorString(String message, ModelMap model) {
		Upitem info = new Upitem();
		info.setError(1);

		return info;
	}

}
